import axios from 'axios'
import router from '../router'

const request = axios.create({
  baseURL: '/user', // 这里配置你的后端接口基础路径
  timeout: 5000
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // token 过期或无效
          localStorage.removeItem('token')
          localStorage.removeItem('userName')
          localStorage.removeItem('userType')
          router.push('/login')
          break
        default:
          console.error('请求错误:', error.response.data)
      }
    }
    return Promise.reject(error)
  }
)

export default request 